<?php


namespace App\Http\Api\Controllers;


use App\Library\JsonData;
use App\Models\CoOrder;
use App\Models\CoUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class DistributionOrderController extends Controller
{
    public function __construct(Request $request)
    {
        // 调用父类前置方法
        parent::__construct();
        $this->api_token = trim($request->header('token'));
        $this->get_user();
        if(empty($this->user_info)){
            return JsonData::error('未登录','',601);
        }
        if($this->user_info->is_type !=1){
            return JsonData::error('不是配送员','',500);
        }
        if($this->user_info->is_shen !=1 || $this->user_info->status !=1){
            return JsonData::error('暂时无法接单','',500);
        }
    }

    /**
     * 订单大厅
     * @param Request $request
     */
    public function order_list(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'school_id'=>'required|integer',
                'order_type'=>'required|in:1,2',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            //赋值
            $order_type = intval($request->get('order_type',1));
            if(!in_array($order_type,[1,2])){
                return JsonData::error('参数错误','',500);
            }
            $where['status'] =1;
            $distribution_type = intval($request->get('distribution_type',1));
            if(in_array($distribution_type,[1,2])){
                $where['distribution_type'] = $distribution_type;
            }
            $school_id = $request->school_id;
            $school_building_id = intval($request->get('school_building_id'));
            if(!empty($school_building_id)){
                $where['school_building_id'] = $school_building_id;
            }

            //查询

            $data = CoOrder::with('usercity')
                ->with('orderexpress')
                ->with('user')
                ->where($where)
                ->where('school_id','=',$school_id)
                ->where('order_type','=',$order_type)
                ->select('id','order_no','distribution_name','distribution_time','order_type','status','pay_status','is_urgent','price','city_id','confirm_time','cancel_time','is_comments','created_at','updated_at')
                ->orderByDesc('is_urgent')
                ->paginate(10);
            return JsonData::success( "返回成功",$data,200);
        } catch (\Throwable $e) {
            DB::rollBack();
            return JsonData::error( $e,"",500);
        }

    }


    /**
     * 订单详情
     */
    public function order_details(Request $request){
        $order_no = $request->get('order_no',0);
        if(empty($order_no)){
            return JsonData::error( "参数错误",'',500);
        }
        $data = CoOrder::with('usercity')
            ->with('orderexpress')
            ->where('order_no','=',$order_no)
            ->first();
        //去除参数
        $type = intval($request->get('type',0));
        if($type !=1){
            unset($data->safety_code);
        }
        unset($data->id);
        return JsonData::success( "返回成功",$data,200);
    }

    /**
     * 配送员抢单
     * @param Request $request
     */
    public function order_grabbing(Request $request){
        $order_no = $request->get('order_no',0);
        if(empty($order_no)){
            return JsonData::error( "参数错误",'',500);
        }
        $data = CoOrder::where('order_no','=',$order_no)->first();
        if($data->status ==1 && $data->pay_status && $data->distribution_user_id ==0){
            DB::beginTransaction();
            $data->status=2;
            $data->distribution_user_id=$this->user_info->id;
            $data->confirm_time = date('Y-m-d H:i:s',time());
            $res = $data->save();
            if($res){
                DB::commit();
                return JsonData::success( "抢单成功",'',200);
            }else{
                DB::rollBack();
                return JsonData::error( "抢单失败",'',500);
            }
        }else{
            return JsonData::error( "订单已被抢",'',500);
        }
    }


    /**
     * 配送员取消订单
     * @param Request $request
     */
    public function cancel_order(Request $request){
        try {
            $order_no = $request->get('order_no',0);
            if(empty($order_no)){
                return JsonData::error( "参数错误",'',500);
            }
            $data = CoOrder::where('distribution_user_id','=',$this->user_info->id)->where('order_no','=',$order_no)->first();
            if((in_array($data->status,[2,3]) && $data->pay_status ==1) || (in_array($data->status,[2,3]) && $data->pay_status ==4)){
                DB::beginTransaction();
                $order_num = sys_config('order_num');//可取消次数
                if($data->is_urgent ==1){
                    //获取加急免除罚时间
                    $order_time = sys_config('urgent_order_time'); //分钟
                    $order_pro = intval(sys_config('urgent_order_price')); //处罚比例
                }else{
                    //获取普通免除罚时间
                    $order_time = sys_config('order_time'); //分钟
                    $order_pro = intval(sys_config('order_price')); //处罚比例
                }
                $order_price = $data->price;
                if($order_pro >0){
                    $order_price =  bcdiv($order_pro * $data->price,100,2);
                }
                if($this->user_info->order_num >=$order_num){
                    //扣钱
                    $res = (new CoUser())->save_user($this->user_info->id,$order_price,2,'取消订单处罚金额-'.$order_price);
                    if($res == false){
                        DB::rollBack();
                        return JsonData::error( "取消订单失败",'',500);
                    }
                }else{
                    //判断是否处罚
                    if((time() - strtotime($data->confirm_time)) > $order_time*60){
                        //处罚
                        $res = (new CoUser())->save_user($this->user_info->id,$order_price,2,'取消订单处罚金额-'.$order_price);
                        if($res == false){
                            DB::rollBack();
                            return JsonData::error( "取消订单失败",'',500);
                        }
                    }else{
                        //免处罚增加取消次数
                        $res = (new CoUser())->save_order_num($this->user_info->id,1);
                        if($res == false){
                            DB::rollBack();
                            return JsonData::error( "取消订单失败",'',500);
                        }
                    }
                }
                //未结单可退款
                if($data->pay_status ==1){
                    //修改订单状态
                    $data->status=5;
                    $data->pay_status=2;
                    $data->cancel_time = date('Y-m-d H:i:s',time());
                    $data->remarks='配送员取消,订单退款';
                    $res = $data->save();
                    if(!$res){
                        DB::rollBack();
                        return JsonData::error( "订单取消失败",'',500);
                    }
                    //退款操作
                    $wechat = Pay::wechat(config('app.wechat'));
                    //未结单退款
                    $order = [
                        'out_trade_no' => $data->order_no,
                        'out_refund_no' => time(),
                        'total_fee' => $data->price*100,
                        'refund_fee' => $data->price*100,
                        'refund_desc' => '服务退款-'.$data->order_no,
                        'type' => "miniapp",
                    ];
                    $result = $wechat->refund($order);
                    if($result['return_code'] =='SUCCESS'){
                        DB::commit();
                        return JsonData::success( "订单取消成功",'',200);
                    }else{
                        DB::rollBack();
                        return JsonData::error( "订单取消失败",'',500);
                    }
                }else{
                    //修改订单状态
                    $data->remarks='配送员取消，免单订单不退款';
                    $data->status=5;
                    $data->cancel_time = date('Y-m-d H:i:s',time());
                    $res = $data->save();
                    if(!$res){
                        DB::rollBack();
                        return JsonData::error( "订单取消失败",'',500);
                    }
                    DB::commit();
                    return JsonData::success( "订单取消成功",'',200);
                }
            }else{
                return JsonData::error( "订单无法取消",'',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }

    }

    /**
     * 获取处罚信息
     */
    public function get_cancel(Request $request){
        try {
            $order_no = $request->get('order_no',0);
            if(empty($order_no)){
                return JsonData::error( "订单无法取消",'',500);
            }
            $data = CoOrder::where('distribution_user_id','=',$this->user_info->id)->where('order_no','=',$order_no)->first();
            if((in_array($data->status,[2,3]) && $data->pay_status ==1) || (in_array($data->status,[2,3]) && $data->pay_status ==4)){
                $info['is_time'] =0; //是否超时
                $info['num'] = intval(sys_config('order_num'));//可取消次数
                $order_pro = 0;//处罚比例
                if($data->is_urgent ==1){
                    //获取加急免除罚时间
                    $info['time'] = intval(sys_config('urgent_order_time')); //分钟
                    $order_pro = intval(sys_config('urgent_order_price')); //处罚金额比例
                }else{
                    //获取普通免除罚时间
                    $info['time'] = intval(sys_config('order_time')); //分钟
                    $order_pro = intval(sys_config('order_price')); //处罚金额比例
                }
                $order_price = $data->price;
                if($order_pro >0){
                    $order_price = bcdiv($order_pro * $data->price,100,2);
                }
                $info['is_k'] =1;
                if($this->user_info->order_num <= $info['num'] ){
                    $info['is_k'] =0;
                }
                $info['user_num'] = $this->user_info->order_num;
                $info['price'] = $order_price;
                //计算是否超时
                $time_num = time() - strtotime($data->confirm_time);
                if($time_num > intval($info['time'])*60){
                    $info['is_time'] =1;
                }
                return JsonData::success( "返回成功",$info,200);
            }else{
                return JsonData::error( "订单无法取消",'',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }

    /**
     * 代取订单确认
     * @param Request $request
     */
    public function take_order(Request $request){
        $validator = Validator::make($request->all(), [
            'order_no' => 'required',
            'code'=>'required', //安全码
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        $order_no = $request->order_no;
        $code = $request->code;
        $data = CoOrder::where('distribution_user_id','=',$this->user_info->id)->where('order_no','=',$order_no)->first();
        if(empty($data)){
            return JsonData::error( "订单不存在",'',500);
        }
        if($data->status !=2){
            return JsonData::error( "该订单无法确认",'',500);
        }
        if($data->safety_code !=$code){
            return JsonData::error( "安全码错误",'',500);
        }
        DB::beginTransaction();
        $data->status = 4;
        $data->close_time = date('Y-m-d H:i:s',time());
        $res = $data->save();
        if(!$res){
            DB::rollBack();
            return JsonData::error( "订单确认失败",'',500);
        }
        //提成比例
        $commission = intval(sys_config('commission'));
        if($commission > 0){
            $price = bcmul($data->price,$commission/100,2);
            //加钱操作
            $res = (new CoUser())->save_user($this->user_info->id,$price,1,'代取订单收入+'.$price);
            if($res == false){
                DB::rollBack();
                return JsonData::error( "订单确认失败",'',500);
            }
        }
        $res = $this->end_order();
        if($res ==false){
            DB::rollBack();
            return JsonData::error( "订单确认失败",'',500);
        }
        DB::commit();
        return JsonData::success( "订单确认成功",'',200);
    }


    /**
     * 代寄订单取货验证接口
     */
    public function send_take_order(Request $request){
        $validator = Validator::make($request->all(), [
            'order_no' => 'required',
            'code'=>'required', //安全码
            'imgs'=>'required'//取件图片
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        $order_no = $request->order_no;
        $code = $request->code;
        $pick_imgs = $request->imgs;
        $data = CoOrder::where('distribution_user_id','=',$this->user_info->id)->where('order_no','=',$order_no)->first();
        if(empty($data)){
            return JsonData::error( "订单不存在",'',500);
        }
        if($data->status !=2){
            return JsonData::error( "该订单无法进行取货确认",'',500);
        }
        if($data->safety_code !=$code){
            return JsonData::error( "安全码错误",'',500);
        }
        $data->pick_imgs = $pick_imgs;
        $data->status = 3; //进行中
        $data->collect_time = date('Y-m-d H:i:s',time());//取货时间
        $res = $data->save();
        if(!$res){
            return JsonData::error( "订单确认失败",'',500);
        }
        return JsonData::success( "订单确认成功",'',200);
    }

    /**
     * 代寄订单完成订单接口
     */
    public function send_order(Request $request){
        $validator = Validator::make($request->all(), [
            'order_no' => 'required',
            'imgs'=>'required'//寄件图片
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        $order_no = $request->order_no;
        $end_imgs = $request->imgs;
        $data = CoOrder::where('distribution_user_id','=',$this->user_info->id)->where('order_no','=',$order_no)->first();
        if(empty($data)){
            return JsonData::error( "订单不存在",'',500);
        }
        if($data->status !=3){
            return JsonData::error( "该订单无法进行确认",'',500);
        }
        DB::beginTransaction();
        $data->end_imgs = $end_imgs;
        $data->status = 4; //进行中
        $data->close_time = date('Y-m-d H:i:s',time());//取货时间
        $res = $data->save();
        if(!$res){
            DB::rollBack();
            return JsonData::error( "订单确认失败",'',500);
        }
        //提成比例
        $commission = intval(sys_config('commission'));
        if($commission > 0){
            $price = bcmul($data->price,$commission/100,2);
            //加钱操作
            $res = (new CoUser())->save_user($this->user_info->id,$price,1,'代取订单收入+'.$price);
            if(!$res){
                DB::rollBack();
                return JsonData::error( "订单确认失败",'',500);
            }
        }
        $res = $this->end_order();
        if($res ==false){
            DB::rollBack();
            return JsonData::error( "订单确认失败",'',500);
        }
        DB::commit();
        return JsonData::success( "订单确认成功",'',200);
    }

    /**
     * 完成订单奖励
     */
    protected function end_order(){
        //获取奖励单数
        $end_num = intval(sys_config('end_num')); //分钟
        if($end_num >0){
            //查询用户是否已奖励
            $reward_num = DB::table('co_user')->where('id',$this->user_info->id)->value('reward_num');
            if($reward_num >1){
                return true;
            }else{
                $start = date('Y-m-d H:i:s',mktime(00, 00, 00, date('m', strtotime(date('Y-m'))), 01));
                $end =  date('Y-m-d H:i:s',mktime(23, 59, 59, date('m', strtotime(date('Y-m')))+1, 00));
                $num = CoOrder::where('status',4)->where('user_id',$this->user_info->id)
                    ->whereBetween('close_time',[$start,$end])
                    ->count();
                if($num >=$end_num){
                    //获取奖励金额
                    $end_price = (float)sys_config('end_price'); //分钟
                    if($end_price >0){
                        //执行奖励
                        $res = (new CoUser())->save_user($this->user_info->id,$end_price,1,'月完成'.$end_num.'单奖励收入+'.$end_price);
                        if(!$res){
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }


    /**
     * 订单列表
     * @param Request $request
     */
    public function order_user_list(Request $request){
        try {
            //赋值
            $order_type = $request->get('order_type',1);
            if(!in_array($order_type,[1,2,3])){
                return JsonData::error('参数错误','',500);
            }
            $where =[];
            $orderBy ='confirm_time';
            //查询
            if($order_type ==1){
                $where['order_type'] =1;
                $where_in =[2,3];
            }else if($order_type ==2){
                $where['order_type'] =2;
                $where_in =[2,3];
            }else{
                $orderBy ='close_time';
                $where_in =[4];
                $type = $request->get('type',1);
                if(!in_array($type,[1,2])){
                    return JsonData::error('参数错误','',500);
                }
                $where['order_type'] =$type;
            }
            $data = CoOrder::with('usercity')
                ->with('orderexpress')
//                ->with('user')
                ->where($where)
                ->orderByDesc($orderBy)
                ->whereIn('status',$where_in)
                ->where('distribution_user_id','=',$this->user_info->id)
                ->select('id','order_no','distribution_name','distribution_time','order_type','status','pay_status','is_urgent','price','city_id','confirm_time','cancel_time','is_comments','created_at','updated_at')
                ->paginate(10);
            return JsonData::success( "返回成功",$data,200);
        } catch (\Throwable $e) {
            DB::rollBack();
            return JsonData::error( $e,"",500);
        }

    }


    /**
     * 订单统计
     * @param Request $request
     */
    public function order_count(Request $request){
        try {
            $data['order1'] = CoOrder::where('order_type',1)->whereIn('status',[2,3])->where('distribution_user_id',$this->user_info->id)->count();
            $data['order2'] = CoOrder::where('order_type',2)->whereIn('status',[2,3])->where('distribution_user_id',$this->user_info->id)->count();
            $data['order3'] = CoOrder::where('status',4)->where('distribution_user_id',$this->user_info->id)->count();
            return JsonData::success( "返回成功",$data,200);
        }catch (\Exception $e){
            DB::rollBack();
            return JsonData::error($e->getMessage(),'',500);
        }
    }

    /**
     * 订单详情
     */
    public function order_user_details(Request $request){
        $order_no = $request->get('order_no',0);
        if(empty($order_no)){
            return JsonData::error( "参数错误",'',500);
        }
        $data = CoOrder::with('usercity')
            ->with('orderexpress')
            ->where('order_no','=',$order_no)
            ->where('distribution_user_id','=',$this->user_info->id)
            ->first();
        //去除参数
        unset($data->id);
        return JsonData::success( "返回成功",$data,200);
    }
}
